﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using FXC.SL.CS.Modal;
using System.Xml.Linq;
using System.Linq;

namespace FXC.SL.CS.ViewModal
{
    public class InstantMarketQuoteViewModal
    {
        ObservableCollection<InstantMarketQuote> _items = new ObservableCollection<InstantMarketQuote>();

        public ObservableCollection<InstantMarketQuote> Items
        {
            get { return _items; }
            set
            {
                _items = value;
            }
        }

        public void UpdateItem(string xmlData)
        {
            XDocument xdoc = XDocument.Parse(xmlData);
            var query = from el in xdoc.Elements("rates").Elements("rate")
                        select el;
            foreach (XElement xe in query)
            {
                string pName = xe.Attribute("name").Value;
                // 如果已经存在
                var queryExist = (from p in _items
                                 where p.ProductName == pName
                                 select p).SingleOrDefault();

                if (queryExist == null)
                {
                    InstantMarketQuote imq = new InstantMarketQuote();
                    imq.ProductName = pName;
                    imq.SellPrice = Convert.ToDecimal(xe.Attribute("bid").Value);
                    imq.BuyPrice = Convert.ToDecimal(xe.Attribute("ask").Value);
                    imq.IsRise = true;
                    Items.Add(imq);
                }
                else
                {
                    decimal newSell, newBuy;
                    newSell = Convert.ToDecimal(xe.Attribute("bid").Value);
                    newBuy=Convert.ToDecimal(xe.Attribute("ask").Value);
                    queryExist.IsRise = (queryExist.SellPrice == newSell ? queryExist.IsRise : queryExist.SellPrice < newSell);
                    queryExist.SellPrice = newSell;
                    queryExist.BuyPrice = newBuy;
                }
            }
        }
    }
}
